package nf;

import java.io.File;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import fraclac.FracLacWrapper;

public class Worker implements Runnable 
{
	private BlockingDeque<File> queue = null;
	private ConcurrentHashMap<String, String> results = null;
	private AtomicInteger counter = null;
	private volatile static int UID = 1;
	private int myID = 0;
	private ImagePreprocessor preprocessor = null;
	private int resizeW = 0;
	private int resizeH = 0;
	
	public Worker(BlockingDeque<File> queue, ConcurrentHashMap<String, String> results, AtomicInteger counter,
			ImagePreprocessor preprocessor, int resizeW, int resizeH)
	{
		this.queue = queue;
		this.results = results;
		this.myID = UID++;
		this.counter = counter;
		this.preprocessor = preprocessor;
		this.resizeW = resizeW;
		this.resizeH = resizeH;
	}

	@Override
	public void run() 
	{
		System.out.println("Worker thread #" + myID + " started.");
		while(!queue.isEmpty())
		{
			File myFile = queue.remove();
			if(myFile == null)
			{
				System.out.println("File is null?");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				continue;
			}
			//ImagePreprocessor proc = new DePaperer();
			//String data = FracLacWrapper.processFile(myFile.getAbsolutePath(), null, proc, 1400, 1054);
			String data = FracLacWrapper.doFile(myFile, preprocessor, resizeW, resizeH);
			
			if(data == null)
			{
				System.out.println("Data is null for " + myFile.getName());
				data = "";
			}
			
			results.put(myFile.getName(), data);
			counter.incrementAndGet();
		}
		System.out.println("Worker thread #" + myID + " died, no more jobs to do.");
	}
	
}
